import logging
from random import randint


from django import http
from django_redis import get_redis_connection
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.verification.constants import IMAGE_CODE_EXPIRED_TIME,SMS_CODE_EXPIRE_TIME,SMS_CODE_FLAG_TIME
from celery_tasks.sms.tasks import send_sms_code
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE
from django_redis import get_redis_connection


class ImageCodeView(View):
    def get(self,request,uuid):
        code,image = captcha.generate_captcha()
        conn = get_redis_connection('code')
        conn.setex('img:%s'%uuid,IMAGE_CODE_EXPIRED_TIME,code)
        return http.HttpResponse(image,content_type='image/jpeg')

logger = logging.getLogger('django')


class SmsCodeView(View):
    def get(self,request,mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code,uuid]):
            return http.HttpResponseBadRequest('参数不全')
        try:
            conn = get_redis_connection('code')
            redis_code = conn.get('img:%s'%uuid)
            if redis_code is None:
                return http.HttpResponseBadRequest('验证码已过期')
            if redis_code.decode().lower() != image_code.lower():
                return http.HttpResponseBadRequest('图片验证码输入错误')
            conn.delete('img:%s' % uuid)



            send_flag = conn.get('send_flag:%s' % mobile)
            if send_flag:

                return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '您是AE86吗?'})






        except Exception as e:
            logger.error(e)
            return http.HttpResponseBadRequest('redis连接错误')

        sms_code = '%06d' % randint(0, 999999)
        # conn.setex('sms:%s' % mobile, SMS_CODE_EXPIRE_TIME, sms_code)

        # conn.setex('send_fla短信g:%s' % mobile,SMS_CODE_FLAG_TIME,1)


        pl = conn.pipeline()
        pl.setex('sms:%s' % mobile, SMS_CODE_EXPIRE_TIME, sms_code)
        pl.setex('send_flag:%s' % mobile,SMS_CODE_FLAG_TIME,1)
        pl.execute()

        send_sms_code.delay(mobile,sms_code)

        # CCP().send_template_sms(mobile, [sms_code, 5],1)
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

